import { useState } from 'react';
import axios from 'axios';
import './PhotoUploader.css';

function PhotoUploader({ onPhotoUploaded }) {
  const [files, setFiles] = useState([]);
  const [previews, setPreviews] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');

  const handleFileChange = (e) => {
    const selectedFiles = Array.from(e.target.files);
    if (selectedFiles.length === 0) return;

    // 验证所有文件
    let hasError = false;
    selectedFiles.forEach(file => {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        setError('请确保所有选择的文件都是图片');
        hasError = true;
        return;
      }

      // 检查文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        setError('每张图片大小不能超过5MB');
        hasError = true;
        return;
      }
    });

    if (hasError) return;

    setError('');
    setFiles(selectedFiles);

    // 创建预览
    const newPreviews = [];
    selectedFiles.forEach(file => {
      const reader = new FileReader();
      reader.onload = () => {
        newPreviews.push(reader.result);
        if (newPreviews.length === selectedFiles.length) {
          setPreviews(newPreviews);
        }
      };
      reader.readAsDataURL(file);
    });
  };

  const handleUpload = async () => {
    if (files.length === 0) {
      setError('请先选择至少一张图片');
      return;
    }

    setUploading(true);
    setError('');

    try {
      const uploadedPhotos = [];
      
      // 逐个上传文件
      for (const file of files) {
        const formData = new FormData();
        formData.append('photo', file);

        const response = await axios.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        uploadedPhotos.push(response.data.file);
      }

      // 上传成功，清空表单
      setFiles([]);
      setPreviews([]);
      
      // 通知父组件更新照片列表
      if (onPhotoUploaded && uploadedPhotos.length > 0) {
        // 将所有上传的照片传递给父组件
        uploadedPhotos.forEach(photo => {
          onPhotoUploaded(photo);
        });
      }
    } catch (err) {
      console.error('上传失败:', err);
      setError(err.response?.data?.message || '上传失败，请重试');
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="photo-uploader">
      <div className="upload-container">
        <div 
          className={`drop-area ${previews.length > 0 ? 'has-preview' : ''}`}
          onClick={() => document.getElementById('file-input').click()}
        >
          {previews.length > 0 ? (
            <div className="preview-container">
              {previews.map((preview, index) => (
                <img key={index} src={preview} alt={`预览 ${index + 1}`} className="preview-image" />
              ))}
            </div>
          ) : (
            <div className="placeholder">
              <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                <circle cx="8.5" cy="8.5" r="1.5"/>
                <polyline points="21 15 16 10 5 21"/>
              </svg>
              <p>点击选择图片或拖放图片到这里</p>
            </div>
          )}
          <input
            type="file"
            id="file-input"
            accept="image/*"
            multiple
            onChange={handleFileChange}
            style={{ display: 'none' }}
          />
        </div>

        {error && <div className="error-message">{error}</div>}

        <button 
          className="upload-button" 
          onClick={handleUpload} 
          disabled={files.length === 0 || uploading}
        >
          {uploading ? '上传中...' : `上传图片${files.length > 0 ? ` (${files.length})` : ''}`}
        </button>
      </div>
    </div>
  );
}

export default PhotoUploader;